import { treeData } from "./data.js";

function createElementsFromStr(str) {
  const container = document.createElement("div");
  container.innerHTML = str;
  return [...container.children];
}

function nodeAddChildren(node, children) {
  children.forEach((child) => node.appendChild(child));
}

class TreeNode {
  constructor(nodeData) {
    this.name = nodeData.name;
    this.children = nodeData.children || [];
    this.indent = nodeData.indent || 0;
    this.isCollapsed = false;
  }

  toggle() {
    this.isCollapsed = !this.isCollapsed;
  }

  render() {
    const div = document.createElement("div");
    div.classList.add("tree-node");

    const contentNodeStr = `<div class="node-content">
    <span class='tree-node-indent'>${"&nbsp;".repeat(
      this.indent * 1
    )}</span><span class='toggle'><i class='${"bi-caret-down-fill"}'></i> </span><span class='check'><i class='${"bi-check-square"}'></i></span>
    <span>${this.name}</span>
    </div>`;

    const [contentNode] = createElementsFromStr(contentNodeStr);
    const toggleNode = contentNode.querySelector(".toggle");

    div.appendChild(contentNode);

    if (this.children.length > 0) {
      toggleNode.addEventListener("click", (event) => {
        event.stopPropagation();
        this.toggle();
        const childrenDiv = div.querySelector(".children");
        childrenDiv.style.display = this.isCollapsed ? "none" : "block";
        toggleNode.innerHTML = `<i class="bi-caret-${
          this.isCollapsed ? "right" : "down"
        }-fill"></i> `;
      });

      const childrenDiv = document.createElement("div");
      childrenDiv.classList.add("children");
      this.children.forEach((child) => {
        child.indent = this.indent + 1;
        return childrenDiv.appendChild(new TreeNode(child).render());
      });
      div.appendChild(childrenDiv);
    } else {
      toggleNode.innerHTML = "&nbsp;&nbsp;";
    }

    return div;
  }
}

class Tree {
  constructor() {
    this.root = new TreeNode(treeData);
  }

  render() {
    const rootDiv = document.getElementById("tree-root");
    rootDiv.appendChild(this.root.render());
  }
}

const tree = new Tree();
tree.render();
